import numpy as np
import umap
import json

# 读取数据
def read_data(filename):
    with open(filename, 'r') as file:
        data = file.readlines()
    data = [line.strip().split('\t') for line in data]
    return data

# 主程序
def main():
    # 读取数据
    data = read_data(r'C:\Users\C\Desktop\NSEVis\src\assets\filtered_DM_label.txt')  # 替换 'your_data.txt' 为你的文件名

    # 提取特征数据
    features = [list(map(int, item[1])) for item in data]  # 假设特征在第二列

    # 将特征转换为numpy数组
    features_array = np.array(features)

    # 使用UMAP进行降维
    reducer = umap.UMAP(n_components=2, random_state=42)
    embedding = reducer.fit_transform(features_array)

    # 将降维结果与节点ID合并，并确保所有浮点数转换为Python的float类型
    results = [{'node': item[0], 'x': float(embedding[i, 0]), 'y': float(embedding[i, 1])} for i, item in enumerate(data)]

    # 保存为JSON
    with open('umap_results_DM.json', 'w') as json_file:
        json.dump(results, json_file, indent=4)

    print("UMAP降维完成，结果已保存为JSON文件。")

if __name__ == "__main__":
    main()